from itertools import groupby

from tqdm import tqdm
import pandas as pd

from src.base import Consts


class SyncRegionIndicator:
    def __init__(self, logger, localDb, dataCenterDb, fcdb, es, enterpriseList):
        self.logger = logger
        self.localDb = localDb
        self.dataCenterDb = dataCenterDb
        self.fcdb = fcdb
        self.es = es
        self.enterpriseList = enterpriseList

    def queryRegionIndicator(self, platform_region_code):
        sql = """
             SELECT `year`,index_code,index_value,b.name  from region_index ri
            left join region_index_calc_settings b on b.code=ri.index_code
            where region_code =%s
        """
        query = self.localDb.Query(sql, (platform_region_code,))
        return query

    # 负面信息初始化
    def update(self):
        for item in tqdm(self.enterpriseList, desc="es数据库-区域指标信息保存/更新中...", position=0):
            platform_region_code = item['_source']['platform_region_code']
            entType = item['_source']['ent_type']
            if entType != 'T002':
                continue
            # qe级别下调
            body = {
                "doc": {
                    "regionIndicator": self.queryRegionIndicator(platform_region_code)
                }
            }
            self.es.update(index=Consts.es_enterpriseList_index, doc_type="test-type", id=item['_id'], body=body)
